<template>
  <a-modal
    title="人员导出"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    okText="确认"
    cancelText="取消"
  >
    <a-spin :spinning="confirmLoading">
      <person-table :manoeuvreId="manoeuvreId" @getPerson="onSelectPerson" v-if="childShow"></person-table>
    </a-spin>
    <a-card
      style="width:100%"
      :tab-list="tabListNoTitle"
      :active-tab-key="this.noTitleKey"
      @tabChange="key => onTabChange(key, 'noTitleKey')"
    >
      <div>
        <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange" style="margin-top: 10px">
          全选
        </a-checkbox>
      </div>
      <a-checkbox-group v-model="checkedList" @change="onChange" style="width: 100%">
        <a-row v-for="(optionRow, i) in splitArray(options[noTitleKey], 4)" :key="i" style="margin-top: 8px">
          <a-col :span="6" v-for="(item, j) in optionRow" :key="j">
            <a-checkbox :value="item">
              {{ item }}
            </a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-card>
  </a-modal>
</template>

<script>
  import PersonTable from '@/components/PersonSelect/PersonTable'
  import { exportPerson } from '../../../../api/basic/soldier'

  // const plainOptions = ['Apple', 'Pear', 'Orange']
  // const defaultCheckedList = ['Apple', 'Orange']
  export default {
    name: 'OutputExcel',
    components: {
      PersonTable
    },
    data () {
      return {
        title: '',
        tabListNoTitle: [
          {
            key: '0',
            tab: '基础数据'
          },
          {
            key: '1',
            tab: '主要经历'
          },
          {
            key: '2',
            tab: '社会关系'
          }
        ],
        noTitleKey: this.$route.query.noTitleKey === undefined ? '0' : this.$route.query.noTitleKey,
        list: '',
        list1: '',
        checkedList: [],
        indeterminate: true,
        checkAll: false,
        options: {
          '0': ['序号', '身份证号码', '身份号', '姓名', '人员类别', '部别', '部职别', '现任职时间', '性别', '曾用名',
            '民族', '出生日期', '入伍日期', '政治面貌', '入党团时间', '军衔', '现军衔时间', '职级', '现职级时间', '文化程度', '婚恋状况',
            '籍贯', '出生地', '入伍地', '家庭住址', '邮政编码', '家庭电话', '手机号码', 'QQ及Email', '休假类型', '应休天数', '路途天数'],
          '1': ['序号', '身份证号码', '姓名', '个人履历', '起止时间', '详情', '证明人'],
          '2': ['序号', '身份证号码', '姓名', '类别',	'关系人姓名', '与本人关系', '关系人身份证', '性别',
            '出生日期', '籍贯', '民族', '现住址', '何部别', '职务或职业', '政治面貌', '宗教信仰']
        },
        socialMap: {
          '序号': 'social_relation_id',
          '身份证号码': 'person_idcard',
          '姓名': 'person_name',
          '类别': 'social_relation_type',
          '关系人姓名': 'social_relation_name',
          '与本人关系': 'social_relation_relationship',
          '关系人身份证': 'social_relation_idcard',
          '性别': 'social_relation_sex',
          '出生日期': 'social_relation_birthday',
          '籍贯': 'social_relation_native_place',
          '民族': 'social_relation_nation',
          '现住址': 'social_relation_current_address',
          '何部别': 'social_relation_work_units',
          '职务或职业': 'social_relation_post',
          '政治面貌': 'social_relation_politics_status',
          '宗教信仰': 'social_relation_religion'
        },
        experienceMap: {
          '序号': 'experience_id',
          '身份证号码': 'person_idcard',
          '姓名': 'person_name',
          '个人履历': 'experience_type',
          '起止时间': 'experience_time',
          '详情': 'experience_main',
          '证明人': 'experience_certifier'
        },
        optionMap: {
          '序号': 'person_id',
          '身份证号码': 'person_idcard',
          '身份号': 'person_card',
          '姓名': 'person_name',
          '人员类别': 'person_type',
          '部别': 'person_department',
          '部职别': 'person_job_title',
          '现任职时间': 'person_tenure',
          '性别': 'person_sex',
          '曾用名': 'person_used_name',
          '民族': 'person_nation',
          '出生日期': 'person_birth_date',
          '入伍日期': 'person_enlistment_date',
          '政治面貌': 'person_politics_status',
          '入党团时间': 'person_party_time',
          '军衔': 'person_military_rank',
          '现军衔时间': 'person_military_rank_time',
          '职级': 'person_rank',
          '现职级时间': 'person_rank_time',
          '文化程度': 'person_edu_level',
          '婚恋状况': 'person_marriage_status',
          '籍贯': 'person_native_place',
          '出生地': 'person_birth_place',
          '入伍地': 'person_enlistment_place',
          '家庭住址': 'person_home_addr',
          '邮政编码': 'person_postcode',
          '家庭电话': 'person_home_phone',
          '手机号码': 'person_phone',
          'QQ及Email': 'person_qq_email',
          '休假类型': 'days_vacation_type',
          '应休天数': 'days_should_rest_days',
          '路途天数': 'days_road_days'
        },
        childShow: false,
        manoeuvreId: undefined,
        manoeuvrePersonItem: '',
        persons: [],
        visible: false,
        confirmLoading: false,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        form: this.$form.createForm(this)
      }
    },
    methods: {
      onTabChange (key, type) {
        this[type] = key
        // if (this.noTitleKey === '0') {
        // } else if (this.noTitleKey === '1') {
        // } else if (this.noTitleKey === '2') {
        // }
        this.checkAll = false
        this.checkedList = []
        this.indeterminate = true
      },
      splitArray (arr, n) {
        const ret = []
        let tmp = []
        for (let i = 0; i < arr.length; i++) {
          tmp.push(arr[i])
          if (i % n === 3) {
            ret.push(tmp)
            tmp = []
          }
        }
        if (tmp.length > 0) {
          ret.push(tmp)
        }
        return ret
      },
      onChange (checkedList) {
        if (this.noTitleKey === '0') {
          this.indeterminate = !!checkedList.length && checkedList.length < this.plainOptions.length
          this.checkAll = checkedList.length === this.plainOptions.length
          if (this.checkAll) {
            this.checkedList = this.plainOptions
          }
        } else if (this.noTitleKey === '1') {
          this.indeterminate = !!checkedList.length && checkedList.length < this.experienceOptions.length
          this.checkAll = checkedList.length === this.experienceOptions.length
          if (this.checkAll) {
            this.checkedList = this.experienceOptions
          }
        } else if (this.noTitleKey === '2') {
          this.indeterminate = !!checkedList.length && checkedList.length < this.socialOptions.length
          this.checkAll = checkedList.length === this.socialOptions.length
          if (this.checkAll) {
            this.checkedList = this.socialOptions
          }
        }
      },
      onCheckAllChange (e) {
        Object.assign(this, {
          checkedList: e.target.checked ? this.options[this.noTitleKey] : [],
          indeterminate: false,
          checkAll: e.target.checked
        })
        // console.log(this.checkedList)
      },
      show () {
        this.persons = []
        this.visible = true
        // this.manoeuvreId = manoeuvreId
        // this.manoeuvrePersonItem = manoeuvrePersonItem
        this.childShow = true
      },
      onSelectPerson (persons) {
        this.persons = persons
      },
      handleSubmit () {
        const _this = this
        const { form: { validateFields } } = this
        if (this.persons.length === 0) {
          this.$message.error('请至少选择一人')
          return
        }
        if (this.checkedList.length === 0) {
          this.$message.error('请至少选择一个字段')
          return
        }
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            let person = {}
            this.list = ''
            for (const i in this.persons) {
              person = this.persons[i]
              const params = {
                ...values,
                personId: person.personId
              }
              console.log(params)
              this.list = this.list + person.personId.toString() + ','
            }
            this.list1 = ''
            if (this.noTitleKey === '0') {
              for (let i = 0; i < this.checkedList.length; i++) {
                this.list1 = this.list1 + this.optionMap[this.checkedList[i]] + ','
                this.title = '人员基础数据.xlsx'
              }
            } else if (this.noTitleKey === '1') {
              for (let i = 0; i < this.checkedList.length; i++) {
                this.list1 = this.list1 + this.experienceMap[this.checkedList[i]] + ','
                this.title = '人员主要经历.xlsx'
              }
            } else if (this.noTitleKey === '2') {
              for (let i = 0; i < this.checkedList.length; i++) {
                this.list1 = this.list1 + this.socialMap[this.checkedList[i]] + ','
                this.title = '人员社会关系.xlsx'
              }
              console.log(this.list1)
            }
            const fd = new FormData()
            fd.append('type', this.noTitleKey)
            fd.append('l1', this.list)
            fd.append('l2', this.list1)
            exportPerson(fd).then(res => {
              this.confirmLoading = false
              const reader = new FileReader()
              reader.readAsText(res)
              reader.onload = (e) => {
                this.downloadFile(_this.title, res)
              }
              this.visible = false
              this.handleCancel()
              this.$emit('ok')
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
        this.childShow = false
        this.noTitleKey = '0'
        this.checkAll = false
        this.checkedList = []
        this.indeterminate = true
      },
      downloadFile (title, data) {
        // for IE
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(data, title)
        } else {
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(data)
          link.download = title
          link.click()
          link.remove()
          window.URL.revokeObjectURL(link.href)
          this.noTitleKey = '0'
          this.checkAll = false
          this.checkedList = []
          this.indeterminate = true
        }
      }
    }
  }
</script>
